import UserInfo from '@/pages/pc/components/UserInfo';
import { Modal, Popover } from 'antd';
import classNames from 'classnames';
import { Link, useModel } from 'umi';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';
import { allGet } from '@/services/pc';
import storage from '@/utils/storage';
import { USERINFO } from '@/common/const';
import useCashOut from '@/hooks/useCashout';
import Empty from '../components/Empty';

const formatNickname = (nickname) => {
  const s = nickname.substring(0, 1);
  const e = nickname.substring(nickname.length - 1, nickname.length);
  if (nickname.length <= 2) return `${s}*`;
  const str = new Array(nickname.length - s.length - e.length).fill('*').join('');
  return s + str + e;
};

const AccountInfo = ({ userInfo, onRefreshInfo }) => {
  /**
   * 我的账单
   */

  const [billVisible, setBillVisible] = useState(false);
  const [billData, setBillData] = useState<any>([]);
  const handleBillClose = () => {
    setBillVisible(false);
  };
  const handleBillVisible = async () => {
    const response = await allGet({
      params: { mod: 'user', do: 'creditlog', perpage: 9999, page: 1, version: 'pc1.0' },
    });
    setBillData(response?.data?.list || []);
    setBillVisible(true);
  };

  const { showCashout, modals, initialValues, showBindAlipay } = useCashOut({
    bindAccountFirst: true,
  });

  const [ldxData, setLdxData] = useState([]);
  useEffect(() => {
    (async () => {
      const response = await allGet({ params: { mod: 'user', do: 'invitebuy', version: 'pc1.0' } });
      setLdxData(response?.data || []);
    })();
  }, []);
  return (
    <div className={styles.accountInfo}>
      {modals}
      <div className={styles.content}>
        <div className={styles.left}>
          <div className={styles.title}>学习币 收入</div>
          <div className={styles.momey}>
            <span className={styles.unit}></span>
            <div className={styles.text}>{userInfo.extcredits1}</div>
          </div>
        </div>

        <div className={styles.buttons}>
          {ldxData?.length > 0 && (
            <Popover
              getPopupContainer={() => document.getElementById('zhy-ldx')!}
              overlayClassName={styles['ldx-propover']}
              destroyTooltipOnHide
              placement="top"
              trigger="hover"
              content={<Ldx data={ldxData} />}
              title={() => null}
            >
              <div className={styles.dx} id="zhy-ldx">
                参加老带新，返现学习币
              </div>
            </Popover>
          )}

          {/*  <div className={styles.alipay} onClick={showBindAlipay}>
            <i className={styles.icon} />
            绑定提现支付宝
            {initialValues.account
              ? `：${initialValues.account}（${formatNickname(initialValues.name)}）`
              : ''}
          </div> */}
          <div className={styles.bill} onClick={handleBillVisible}>
            我的账单
          </div>
          {/*   <div className={styles.tx} onClick={showCashout}>
            提现
          </div> */}
        </div>
      </div>

      <Modal
        destroyOnClose
        className={classNames(styles.myModal, styles.billModal)}
        visible={billVisible}
        width={390}
        footer={null}
        onCancel={handleBillClose}
        centered
        maskClosable
      >
        <div className={styles.header}>我的账单</div>
        <div className={styles.body}>
          {billData.length <= 0 ? (
            <Empty style={{ margin: '20px auto' }} />
          ) : (
            billData.map((item) => {
              const isAdd = Number(item.extcredits1) > 0;
              return (
                <div className={styles.item} key={item.dateline}>
                  <div className={styles.left}>
                    <div className={styles.name}>{item.title}</div>
                    <div className={styles.time}>{item.dateline}</div>
                  </div>
                  <div className={classNames(styles.money, { [styles.add]: isAdd })}>
                    {isAdd ? `+${item.extcredits1}` : item.extcredits1}
                  </div>
                </div>
              );
            })
          )}
        </div>
      </Modal>
    </div>
  );
};

const Ldx = ({ data = [] as any[] }) => {
  return (
    <div className={styles.ldx}>
      {data?.map((item) => (
        <div
          onClick={() => window.open(`/center/courses/detail/${item.classid}`)}
          key={item.classid}
          className={styles.item}
        >
          {item.name}
        </div>
      ))}
    </div>
  );
};

const CjjoyQuan = ({ userInfo }) => {
  return (
    <div className={styles.cjjoyQuanWrapper}>
      <div className={styles.cjjoyQuan}>
        <div className={styles.left}>
          <i className={styles.icon} />
          <span className={styles.text}>CGJOY券：</span>
          <div className={styles.num}>{userInfo.extcredits2}</div>
        </div>
        <a className={styles.button}>
          去使用 <i className={styles.icon} />
        </a>
      </div>
    </div>
  );
};

const YhqEmpty = () => {
  return (
    <div className={styles.yhqEmpty}>
      <i className={styles.icon} />
      暂无优惠券
    </div>
  );
};
const Yhq = () => {
  const [data, setData] = useState<any>([]);
  useEffect(() => {
    (async () => {
      const response = await allGet({
        params: { mod: 'coupon', do: 'list', perpage: 9999, page: 1, version: 'pc1.0' },
      });
      setData(response?.data?.list || []);
    })();
  }, []);
  const zc = data.filter((item) => item.status == 1);
  const gq = data.filter((item) => item.status == -2);
  return (
    <div className={styles.yhqWrapper}>
      <div className={styles.yhq}>
        {(zc.length && gq.length) <= 0 ? (
          <YhqEmpty />
        ) : (
          <>
            {zc.length > 0 && (
              <div className={styles.section}>
                <div className={styles.header}>优惠券（{zc.length}）</div>
                <div className={styles.body}>
                  {zc.map((item) => (
                    <Link
                      to={`/center/courses/detail/${item.classid}`}
                      key={item.coupon}
                      className={classNames(styles.item, styles.actived)}
                    >
                      <div className={styles.content}>
                        <div className={styles.left}>
                          <div className={styles.num}>¥{item.userprice}</div>
                          {/*     <div className={styles.mj}>满1000减500</div> */}
                        </div>

                        <div className={styles.center}>
                          <div className={styles.name}>{item.name}</div>
                          <div className={styles.time}>时间：{item.deadline}</div>
                        </div>
                        <div className={styles.right}>使用</div>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            )}
            {gq.length > 0 && (
              <div className={styles.section}>
                <div className={styles.header}>优惠券（{gq.length}）</div>
                <div className={styles.body}>
                  {gq.map((item) => (
                    <div key={item.coupon} className={classNames(styles.item)}>
                      <div className={styles.content}>
                        <div className={styles.left}>
                          <div className={styles.num}>¥{item.userprice}</div>
                          {/*  <div className={styles.num}>¥1000</div>
                          <div className={styles.mj}>满1000减500</div> */}
                        </div>

                        <div className={styles.center}>
                          <div className={styles.name}>{item.name}</div>
                          <div className={styles.time}>时间：已过期</div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

const Index = () => {
  // 获取用户资料
  const [loading, setLoading] = useState<any>(true);
  const { getUseInfo, userInfo } = useModel('user');

  const localUserInfo = useRef<any>(storage.get(USERINFO) || {});
  // const init = async (showLoading = true) => {
  // }
  // useEffect(() => {
  //     init()
  // }, [userInfo]);
  return (
    <div className={styles.page}>
      <UserInfo edit userInfo={userInfo} onRefreshInfo={getUseInfo} />
      <AccountInfo userInfo={userInfo} onRefreshInfo={getUseInfo} />

      {/* <CjjoyQuan userInfo={userInfo} /> */}
      <Yhq />
    </div>
  );
};

export default Index;
